package sealte.hvpms.servlet.vp;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sealte.hvpms.dao.impl.PollDAOImpl;
import sealte.hvpms.dao.impl.PollOptionDAOImpl;
import sealte.hvpms.pojo.Poll;
import sealte.hvpms.pojo.PollOption;
import sealte.hvpms.pojo.UserCreate;

import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
import com.oreilly.servlet.multipart.FileRenamePolicy;

public class VPAdd extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response); 
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setHeader("Cache-Control", "no-cache");
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html");
		
		UserCreate uc = (UserCreate)request.getSession().getAttribute("UserCreate");
		PrintWriter out = response.getWriter();
		if(uc!=null){
			String message = "";
			Poll poll = (Poll)request.getSession().getAttribute("vp_add1");
			if(poll!=null){
				boolean isOK = false;
				PollDAOImpl pb = new PollDAOImpl();
				boolean flag1 = pb.isDuplicated(poll.getName(), poll.getBuilder());
				if(!flag1){
					boolean flag2 = pb.addNew(poll);
					if(flag2){
						int poll_id = pb.getID(poll.getName(), poll.getBuilder());
						if(poll_id!=0){
							int options = poll.getOptions();
							int maxPostSize = options * 1024 * 1024;
							try{
								String user_images_path = "/upload_Images"+"/"+String.valueOf(uc.getId());
								String URLpath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+user_images_path+"/";
								String realPath = this.getServletContext().getRealPath("");
								String user_path = realPath + user_images_path;
								File file = new File(user_path);
								file.mkdirs();
								FileRenamePolicy policy = new DefaultFileRenamePolicy();
								MultipartRequest multi = new MultipartRequest(request,user_path,maxPostSize,"UTF-8",policy);
								Enumeration<?> images = multi.getFileNames();
								while(images.hasMoreElements()){
									String name = (String)images.nextElement();
									String po_id = name.substring(5);
									String option_content = multi.getParameter("content"+po_id);
									String option_link = multi.getParameter("link"+po_id);
									File f = multi.getFile(name);
									PollOptionDAOImpl pob = new PollOptionDAOImpl();
									PollOption po = new PollOption();
									po.setContent(option_content);
									po.setId(Integer.parseInt(po_id));
									po.setLink(option_link);
									po.setPollid(poll_id);
									if(f!=null){
										String oldFileName = multi.getFilesystemName(name);
										int idx = oldFileName.lastIndexOf(".");
										String ext = oldFileName.substring(idx);
										String newFileName = String.valueOf(poll_id)+"-"+po_id+ext;
										File serverFile = new File(user_path+"/"+ newFileName);
										f.renameTo(serverFile);
										String URLFileName = URLpath + newFileName;
										po.setImage(URLFileName);
									}else{
										po.setImage("");
									}
									boolean flag3 = pob.addNew(po);
									if(flag3){
										isOK = true;
									}else{
										message = "添加投票-选项信息失败";
									}
								}
							}catch(Exception e){
								String message_Exce = e.getMessage();
								if(message_Exce.indexOf("Posted content length of")!=-1){
									message = "您上传的图片中有些超过了最大允许上传文件大小[1MB]，上传失败";
								}else{
									message = "上传失败，请联系开发者";
								}
							}
						}else{
							message = "系统出错，请联系开发者";
						}
					}else{
						message = "新增投票信息失败";
					}
				}else{
					message = "相同的投票[标题]已存在";
				}
				if(isOK){
					request.getRequestDispatcher("home/vp_preview.jsp").forward(request, response);
				}else{
					request.setAttribute("message_addpoll", message);
					request.getRequestDispatcher("home/vp_add.jsp").forward(request, response);
				}
			}else{
				out.println("系统错误，请联系开发者");
			}
		}else{
			out.println("谢绝跨路径访问");
		}
	}
}
